<?php

namespace Home\Controller;

use Think\Controller;

//加载commons下的functions.php自定义函数库
load("@.functions");

class FishplaceController extends Controller {

    public function index() {
        //$this->show('<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.8em; font-size: 36px } a,a:hover,{color:blue;}</style><div style="padding: 24px 48px;"> <h1>:)</h1><p>欢迎使用 <b>ThinkPHP</b>！</p><br/>版本 V{$Think.version}</div><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_55e75dfae343f5a1"></thinkad><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script>','utf-8');

        $this->display();
    }

    function fishplace_list() {
        $fishplaces = D("fishery_nearby");
        $total = $fishplaces->count();
//        show_bug($total);
        $pageSize = $_GET['pageSize'];
        if ($pageSize == '' || !is_numeric($pageSize) || $pageSize <= 0) {
            $pageSize = 10;
        }
        $page = new \Component\Page($total, $pageSize);
        $sql = "select * from dy_fishery_nearby " . $page->limit;

        $info = $fishplaces->query($sql);
        $pageInfo = $page->fpage();
        $this->assign('pageInfo', $pageInfo);
        $this->assign("fishplaces", $info);
//        show_bug($info);
//        die();
//        $this->assign("uu", "umgsai");
        $this->display();
    }

    function fishplace_detail() {
        $id = $_GET['id'];
        $Fishery_nearbyModel = new \Common\Model\Fishery_nearbyModel();
        $fishery_nearby = $Fishery_nearbyModel->get_fishery_nearby($id);
        $this->assign("fishplace", $fishery_nearby);

        //////查出该钓场的图片
        $id_in_that_tab = $id;
        $Dic_tableModel = new \Common\Model\Dic_tableModel();
        $table_id = $Dic_tableModel->get_id_by_name("dy_fishery_nearby")['id'];
        $ImageModel = new \Common\Model\ImageModel();
        $imageList = $ImageModel->where("table_name = 'dy_fishery_nearby' and id_in_that_tab =" . $id_in_that_tab)->select();
        $this->assign("imageList", $imageList);
//        echo $Dic_tableModel->getLastSql();
//        die();

        $this->display();
    }

    function upload_fishplace_pic() {
        /**
         * upload.php
         *
         * Copyright 2013, Moxiecode Systems AB
         * Released under GPL License.
         *
         * License: http://www.plupload.com/license
         * Contributing: http://www.plupload.com/contributing
         */
#!! IMPORTANT:
#!! this file is just an example, it doesn't incorporate any security checks and
#!! is not recommended to be used in production environment as it is. Be sure to
#!! revise it and customize to your needs.
// Make sure file is not cached (as it happens for example on iOS devices)
        header("Content-Type: text/html; charset=utf-8");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");


// Support CORS
// header("Access-Control-Allow-Origin: *");
// other CORS headers if any...
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }


        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }

// header("HTTP/1.0 500 Internal Server Error");
// exit;
// 5 minutes execution time
        @set_time_limit(5 * 60);

// Uncomment this one to fake upload time
        usleep(5000);

// Settings
// $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        $date = date("Y-m-d H:i:s"); //2015-05-13 16:29:37
        $year = substr($date, 0, 4); //2015
        $month = substr($date, 5, 2); //05
        $day = substr($date, 8, 2); //13
        $dir = './Public/uploads/image/' . $year . '/' . $month . '/' . $day . '/';
        create_dir($dir); //调用公共函数
//        $targetDir = 'upload_tmp';
//        $uploadDir = 'upload';
        $uploadDir = $dir;
        $targetDir = $dir . "/upload_tmp";

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }

// Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }

// Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
//        echo $_FILES["file"]["type"];
        $exten = explode('.', $fileName);
        //echo end($exten);//文件后缀名
        //die();

        $md5File = @file('md5list.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $md5File = $md5File ? $md5File : array();

        if (isset($_REQUEST["md5"]) && array_search($_REQUEST["md5"], $md5File) !== FALSE) {
            die('{"jsonrpc" : "2.0", "result" : null, "id" : "id", "exist": 1}');
        }

        $storeFileName = create_uuid("fishery_") . "." . end($exten);
//        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $filePath = $targetDir . $storeFileName;
//        $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        $uploadPath = $uploadDir . $storeFileName;

//        echo $uploadPath;//直接存到数据库
//        die();
// Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;


// Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


// Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }

            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }

        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }

        @fclose($out);
        @fclose($in);

        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
        }

        $image['img_url'] = $uploadPath;
        $image['img_name'] = $_FILES["file"]["name"];
        $Dic_tableModel = new \Common\Model\Dic_tableModel();
        //$image['table_id'] = $Dic_tableModel->get_id_by_name("dy_fishery_nearby")['id'];
        $image['table_name'] = "dy_fishery_nearby";
        $image['id_in_that_tab'] = $_POST['id_in_that_tab'];
        $image['memo'] = $_POST['fishery_name'] . "的照片";
        $ImageModel = new \Common\Model\ImageModel();
        $image_id = $ImageModel->add($image);
        echo $ImageModel->getLastSql();
        die();
//        show_bug($image);
// Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    function jRating() {
        $aResponse['error'] = false;
        $aResponse['message'] = '';

// ONLY FOR THE DEMO, YOU CAN REMOVE THIS VAR
        $aResponse['server'] = '';
// END ONLY FOR DEMO


        if (isset($_POST['action'])) {
            if (htmlentities($_POST['action'], ENT_QUOTES, 'UTF-8') == 'rating') {
                /*
                 * vars
                 */
                $id = intval($_POST['idBox']);
                $rate = floatval($_POST['rate']);
                //echo $id;
               // echo '<br/>'.$rate;

                // YOUR MYSQL REQUEST HERE or other thing :)
                /*
                 *
                 */

                // if request successful
                $success = true;
                // else $success = false;
                // json datas send to the js file
                if ($success) {
                    $aResponse['message'] = 'Your rate has been successfuly recorded. Thanks for your rate :)';

                    // ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER
                    $aResponse['server'] = '<strong>Success answer :</strong> Success : Your rate has been recorded. Thanks for your rate :)<br />';
                    $aResponse['server'] .= '<strong>Rate received :</strong> ' . $rate . '<br />';
                    $aResponse['server'] .= '<strong>ID to update :</strong> ' . $id;
                    // END ONLY FOR DEMO

                    echo json_encode($aResponse);
                } else {
                    $aResponse['error'] = true;
                    $aResponse['message'] = 'An error occured during the request. Please retry';

                    // ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER
                    $aResponse['server'] = '<strong>ERROR :</strong> Your error if the request crash !';
                    // END ONLY FOR DEMO


                    echo json_encode($aResponse);
                }
            } else {
                $aResponse['error'] = true;
                $aResponse['message'] = '"action" post data not equal to \'rating\'';

                // ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER
                $aResponse['server'] = '<strong>ERROR :</strong> "action" post data not equal to \'rating\'';
                // END ONLY FOR DEMO


                echo json_encode($aResponse);
            }
        } else {
            $aResponse['error'] = true;
            $aResponse['message'] = '$_POST[\'action\'] not found';

            // ONLY FOR THE DEMO, YOU CAN REMOVE THE CODE UNDER
            $aResponse['server'] = '<strong>ERROR :</strong> $_POST[\'action\'] not found';
            // END ONLY FOR DEMO


            echo json_encode($aResponse);
        }
    }

}
